package fi.foyt.cs.persistence.dao.oauth;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.oauth.AuthenticatedUserToken;

public class AuthenticatedUserTokenDAO extends GenericDAO<AuthenticatedUserToken> {

  public AuthenticatedUserToken create(Long authenticatedUserId, String token) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      AuthenticatedUserToken authenticatedUserToken = new AuthenticatedUserToken();
      authenticatedUserToken.setAuthenticatedUserId(authenticatedUserId);
      authenticatedUserToken.setToken(token);
      entityManager.persist(authenticatedUserToken);
      entityManager.getTransaction().commit();
      return authenticatedUserToken;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public AuthenticatedUserToken findByAuthenticatedUserId(Long authenticatedUserId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUserToken o where authenticatedUserId = :authenticatedUserId");
    query.setParameter("authenticatedUserId", authenticatedUserId);
    return getSingleResult(query);
  } 
  
  public AuthenticatedUserToken findByToken(String token) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUserToken o where token = :token");
    query.setParameter("token", token);
    return getSingleResult(query);
  } 
  
  public AuthenticatedUserToken findByAuthenticatedUserIdAndToken(Long authenticatedUserId, String token) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUserToken o where authenticatedUserId = :authenticatedUserId and token = :token");
    query.setParameter("authenticatedUserId", authenticatedUserId);
    query.setParameter("token", token);
    return getSingleResult(query);
  }
  
  @SuppressWarnings("unchecked")
  public List<AuthenticatedUserToken> listByAuthenticatedUserId(Long authenticatedUserId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUserToken o where authenticatedUserId = :authenticatedUserId");
    query.setParameter("authenticatedUserId", authenticatedUserId);
    return query.getResultList();
  }
}
